package com.linko.intelligent.common.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class DateUtil {

    private static final Logger logger = LoggerFactory.getLogger(DateUtil.class);

    private static String dateTimePattern = "yyyy-MM-dd HH:mm:ss";
    private static SimpleDateFormat dateTimeFormat = new SimpleDateFormat(dateTimePattern);

    private static String timePattern = "HH:mm:ss";
    private static SimpleDateFormat timeFormat = new SimpleDateFormat(timePattern);

    private static String datePattern = "yyyy-MM-dd";
    private static SimpleDateFormat dateFormat = new SimpleDateFormat(datePattern);

    public static String getPatternDateTime(Date date) {
        return dateTimeFormat.format(date);
    }

    public static String getNowPatternDateTime() {
        return dateTimeFormat.format(new Date());
    }

    public static String getPatternDate(Date date) {
        return dateFormat.format(date);
    }

    public static String getPatternNowDate() {
        return dateFormat.format(new Date());
    }

    public static String getPatternTime(Date date) {
        return dateFormat.format(date);
    }

    public static String getPatternNowTime() {
        return timeFormat.format(new Date());
    }

    //字符串获取时间
    public static Date getDateTimeFromStr(String str) {
        try {
            return dateTimeFormat.parse(str);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
    }

    //字符串获取时间戳
    public static Long getStampFormStr(String str) {
        try {
            if (str.length() > 11) {
                return dateTimeFormat.parse(str).getTime();
            } else {
                return timeFormat.parse(str).getTime();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
    }

    //时间戳获取字符串
    public static String getStrFormStamp(long stamp) {
        Date date = new Date(stamp);
        return dateTimeFormat.format(date);
    }

    //获取今日开始时间 字符串
    public static String getTodayStartTimeStr() {
        return formatStartDateTime(getNowPatternDateTime());
    }

    //获取今日开始时间字符串
    public static Long getTodayStartTimeStemp() {
        return getStampFormStr(formatStartDateTime(getNowPatternDateTime()));
    }

    //获取今日结束时间 字符串
    public static String getTodayEndTimeStr() {
        return formatEndDateTime(getNowPatternDateTime());
    }

    //获取今日结束时间字符串
    public static Long getTodayEndTimeStemp() {
        return getStampFormStr(formatStartDateTime(getNowPatternDateTime()));
    }


    public static String addDate(int day, int hour) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, day);
        calendar.add(Calendar.HOUR, hour);
        Date date = calendar.getTime();
        return getPatternDateTime(date);
    }

    public static String addDateTime(int day, int hour, int minute, int second) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, day);
        calendar.add(Calendar.HOUR, hour);
        calendar.add(Calendar.MINUTE, minute);
        calendar.add(Calendar.SECOND, second);
        Date date = calendar.getTime();
        return getPatternDateTime(date);
    }

    public static String addDateTime(String dateTime, int year, int month, int week, int day, int hour, int minute, int second) {
        Calendar calendar = Calendar.getInstance();
        if (StringUtils.isNotBlank(dateTime)) {
            calendar.setTime(getDateTimeFromStr(dateTime));
        }
        calendar.add(Calendar.YEAR, year);
        calendar.add(Calendar.MONTH, month);
        calendar.add(Calendar.WEEK_OF_YEAR, week);
        calendar.add(Calendar.DAY_OF_YEAR, day);
        calendar.add(Calendar.HOUR, hour);
        calendar.add(Calendar.MINUTE, minute);
        calendar.add(Calendar.SECOND, second);
        Date date = calendar.getTime();
        return getPatternDateTime(date);
    }

    public static String CRDate(String creTime) {
        if (creTime.length() > 10)
            return creTime;
        else
            return creTime + " 00:00:00";
    }

    public static String formatStartDateTime(String creTime) {

        if (creTime.length() < 10) {
            return null;
        }
        creTime = creTime.substring(0, 10);

        return creTime + " 00:00:00";
    }

    public static String formatEndDateTime(String creTime) {
        if (creTime.length() < 10) {
            return null;
        }

        creTime = creTime.substring(0, 10);

        return creTime + " 23:59:59";
    }


    /**
     * end   Time 2018-07-07   转换  2018-07-07 23:59:59
     *
     * @param endTime 为右参数
     */

    public static String ENDate(String endTime) {
        if (endTime.length() > 10)
            return endTime;
        else
            return endTime + " 23:59:59";
    }

    public static String monthForCreTime(String string) {

        return string + "-00 00:00:00";
    }

    public static String monthForEndTime(String string) {

        return string + "-31 23:59:59";
    }


    /**
     * get first date of given month and year
     *
     * @param year
     * @param month
     * @return
     */
    public static String getFirstDayOfMonth(int year, int month) {
        String monthStr = month < 10 ? "0" + month : String.valueOf(month);
        return year + "-" + monthStr + "-" + "01";
    }

    /**
     * get the last date of given month and year
     *
     * @param year
     * @param month
     * @return
     */
    public static String getLastDayOfMonth(int year, int month) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month - 1);
        calendar.set(Calendar.DATE, 1);
        calendar.add(Calendar.MONTH, 1);
        calendar.add(Calendar.DAY_OF_YEAR, -1);
        return calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1) + "-" +
                calendar.get(Calendar.DAY_OF_MONTH);
    }

    /**
     * get Calendar of given year
     *
     * @param year
     * @return
     */
    private static Calendar getCalendarFormYear(int year) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        cal.set(Calendar.YEAR, year);
        return cal;
    }

    /**
     * get start date of given week no of a year
     *
     * @param year
     * @param weekNo
     * @return
     */
    public static String getStartDayOfWeekNo(int year, int weekNo) {
        Calendar cal = getCalendarFormYear(year);
        cal.set(Calendar.WEEK_OF_YEAR, weekNo);
        return cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-" +
                cal.get(Calendar.DAY_OF_MONTH);

    }

    /**
     * get the end day of given week no of a year.
     *
     * @param year
     * @param weekNo
     * @return
     */
    public static String getEndDayOfWeekNo(int year, int weekNo) {
        Calendar cal = getCalendarFormYear(year);
        cal.set(Calendar.WEEK_OF_YEAR, weekNo);
        cal.add(Calendar.DAY_OF_WEEK, 6);
        return cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-" +
                cal.get(Calendar.DAY_OF_MONTH);
    }

    //目标时间是否在区间内
    public static boolean checkDateTimeInSection(String tarTime, String start, String stop) {
        try {
            Date nowTime = dateTimeFormat.parse(tarTime);
            Date startTime = dateTimeFormat.parse(start);
            Date endTime = dateTimeFormat.parse(stop);
            Calendar date = Calendar.getInstance();
            date.setTime(nowTime);
            Calendar begin = Calendar.getInstance();
            begin.setTime(startTime);
            Calendar end = Calendar.getInstance();
            end.setTime(endTime);
            if (date.after(begin) && date.before(end)) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static Long timeDistance(String timeOne, String timeTwo) {

        try {
            Long time1 = timeFormat.parse(timeOne).getTime();
            Long time2 = timeFormat.parse(timeTwo).getTime();
            Long diatance = Math.abs(time1 - time2);
            return diatance / 1000L / 60;//相差的分钟
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }

    }

    public static Long subtract(String timeOne, String timeTwo) {
        try {
            Long time1 = dateTimeFormat.parse(timeOne).getTime();
            Long time2 = dateTimeFormat.parse(timeTwo).getTime();
            return time1 - time2;//相差
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    //将时间分割为今天和前几天
    public static HashMap<String, List<String>> splitTime(String startTime, String endTime) {
        List<String> hh = new ArrayList<>();
        List<String> tt = new ArrayList<>();
        HashMap<String, List<String>> map = new HashMap<>();
        try {
            if (endTime == null) {
                endTime = getNowPatternDateTime();
            }
            Date todayStartTime = dateTimeFormat.parse(formatStartDateTime(getPatternNowDate()));
            Date eTime = dateTimeFormat.parse(formatEndDateTime(endTime.substring(0, 10)));
            if (StringUtils.isNotBlank(startTime)) {
                Date sTime = dateTimeFormat.parse(formatStartDateTime(startTime.substring(0, 10)));
                if (sTime.getTime() < todayStartTime.getTime()) {
                    hh.add(dateTimeFormat.format(sTime));
                    hh.add(dateTimeFormat.format(todayStartTime));
                    map.put("-1", hh);
                }
            } else {
                hh.add(null);
                hh.add(dateTimeFormat.format(todayStartTime));
                map.put("-1", hh);
            }
            tt.add(dateTimeFormat.format(todayStartTime));
            tt.add(dateTimeFormat.format(eTime));
            map.put("1", tt);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    //将时间分割为一天一天的
    public static List<String> splitDate(String startDate, String endDate) {
        List<String> dates = new ArrayList<>();
        Date sd = null;
        Date ed = null;
        try {
            sd = dateTimeFormat.parse(startDate);
            ed = dateTimeFormat.parse(endDate);
        } catch (Exception e) {
            logger.debug(e.getMessage());
            return dates;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(sd);
        while (calendar.getTime().before(ed) || calendar.getTime().compareTo(ed) == 0) {
            dates.add(dateTimeFormat.format(calendar.getTime()));
            calendar.add(Calendar.DAY_OF_YEAR, 1);
            if (dates.size() > 365) {
                return dates;
            }
        }
        return dates;
    }

    //将时间按照间隔（秒）分隔
    public static List<String> splitDateTimeByInterval(String startDate, String endDate, int interval) {
        List<String> dates = new ArrayList<>();
        Date sd = null;
        Date ed = null;
        try {
            sd = dateFormat.parse(startDate);
            ed = dateFormat.parse(endDate);
        } catch (Exception e) {
            logger.debug(e.getMessage());
            return dates;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(sd);
        while (calendar.getTime().before(ed)) {
            dates.add(dateFormat.format(calendar.getTime()));
            calendar.add(Calendar.SECOND, interval);
            if (dates.size() > 3650) {
                return dates;
            }
        }
        dates.add(endDate);
        return dates;
    }


}
